<?php
// +----------------------------------------------------------------------
// | Description: 用户
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\admin\model;

use think\Db;
use app\admin\model\Common;
use com\verify\HonrayVerify;

class Mrelated extends Common
{

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如微信模块用weixin作为数据表前缀
     */
    protected $name = 'apply';
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $autoWriteTimestamp = DATETIME;
    // protected $insert = [
    //     'status' => 1,
    // ];
  


    public function getsexAttr($value)
    {
        $type = [0=>'女',1=>'男',2=>"未知"];
        return $type[$value];
    }

    /**
     * 功能:  m1詳情頁面
     * @Author   zhanhuiping
     * @email    18702529695@163.com
     * @DateTime 2017-09-07
     * @param    string              $id [description]
     * @return   [type]                  [description]
     */
    public function getDataById($id = '')
    {

        $data=$this->alias('a')
            ->join('qh_user_info b','a.uid = b.uid')
            ->field('a.huishou_visit,a.contract_number,a.delay_rate,a.credit_rate*a.period*a.money as rental,a.mobile_type,b.city,b.payday,b.wechat_id,a.name,a.phone,b.age,b.sex,b.qq,b.zhima,b.province,b.id_card_img1,
                    b.id_card_img2,b.id_card_img3,b.tb_address,b.wx_wallet,b.alipay_bill,
                    b.wyjt_img,b.wyjt_hk_img,b.open_gid,b.id_card,b.mon_income,b.company,
                    b.company_ads,a.uid,a.money,a.time,a.check_aid,a.check_time,a.check2_aid,
                    a.check2_time,a.merchandiser,a.treasurer,a.fk_time,a.hk_time,a.period,
                    a.appoint_time,a.order_number,a.rate,a.overdue_rate,a.service_rate,
                    a.procedure_rate,a.credit_rate,a.review,a.remark,b.operator_outUniqueId,a.meets,a.meets3,b.uid,a.upload_img,a.status,a.transfer_info,a.return_visit,a.refuse_to_lend_money,b.address,b.wechat_img,b.negative_img,b.zmf,b.job,a.transfer,a.merchandiser2,b.directories,cuishou_tips')
            ->where('a.id',$id)
            ->find();
 
         $uid = $data['uid'];
         $data['showlist'] = json_decode($data['meets']);
         $data['showlist3'] = json_decode($data['meets3'], true);

         $list = Db::name('admin_condition')->where("(status=1 OR uid=$uid) AND step=1")->field('id,content')->select();
         $data['list'] = $list;
         $list3 = Db::name('admin_condition')->where("(status=1 OR uid=$uid) AND step=3")->field('id,content,beizhu')->select();
         $showArr = [];
         if(is_array($data['showlist3'])) {
             foreach ($data['showlist3'] as $key => $value) {
                 $showArr[] = $value['id'];
             }
         }

         foreach ($list3 as $key => $value) {
             if(in_array($value['id'], $showArr)){
                $list3[$key]['pass'] = 0;
             }else{
                $list3[$key]['pass'] = 1;
             }
         }

         $data['list3'] = $list3;

        // 初审员
         $mapa['id'] = $data['check_aid'];
         $data['check_username'] = Db::name('admin_user')->field('username')->where($mapa)->find();
        
        //复审员
        $map1['id'] = $data['check2_aid'];
        $data['check2_username'] = Db::name('admin_user')->field('username')->where($map1)->find();
         
        //跟单员
        $map2['id'] = $data['merchandiser'];
        $data['merchandiser'] = Db::name('admin_user')->field('username')->where($map2)->find();
        
        //财务员
        $map3['id'] = $data['treasurer'];
        $data['treasurer'] = Db::name('admin_user')->field('username')->where($map3)->find();
        $map['uid'] = $data['uid'];
  
        $username = Db::name('user')->where($map)->field('username')->find();
        $data['username']=$username;
        
        $bz['apply_id'] = $id;
        $bzs = Db::name('apply_bz')->field('is_friends,is_loans,remarks')->where($bz)->find();
        if(!$bzs)
        {
          $bzs['is_friends'] =0;
          $bzs['is_loans']   =0;
        }
        if(!$bzs['remarks'])
        {
            $bzs['remarks'] ='';
        }
        $data['bzs'] = $bzs;
        $list1 = Db::name('reminder_note')
                                 ->field('admin_uid,contact_name,reminder_status,days_overdue,reminder_time,contact_type,repay_money')
                                 ->where($bz)
                                 ->select();
        foreach($list1 as $key=>$value)
        {
             $mapnote['id'] = $value['admin_uid'];
             $admin = Db::name('admin_user')->where($mapnote)->field('username')->find();

             $list1[$key]['username'] = $admin['username']; 
             $data['list1'] = $list1;
        }

        $maps['uid'] = $uid;


         //历史借款记录
        $historyrecord = $this
            ->where($map)
            ->with(['predelay'])
            ->field('uid,id,fourth_claim_date,third_claim_date,time,remark,review,time,phone,status,order_number,check_aid,check_time,check2_aid
          ,check2_time,merchandiser,merchandiser2,treasurer,fk_time,hk_time,money,appoint_time,name,phone,return_visit,refuse_to_lend_money')->select();
        $historyrecord = modelo2array($historyrecord);
        foreach($historyrecord as $key=>$value)
         {
            $map1['id'] = $value['check_aid'];//初审员
            // $map2['id'] = $value['check2_aid'];
            $map3['id'] = $value['merchandiser'];//m0跟单
            $map4['id'] = $value['treasurer'];//财务员
            $map4['id'] = $value['merchandiser2'];//财务员
            
            $check_aiddata = Db('admin_user')->field('username')->where($map1)->find();
            // $check2_aiddata = Db('admin_user')->field('username')->where($map2)->find();
            $merchandiserdata = Db('admin_user')->field('username')->where($map3)->find();
            $treasurerdata = Db('admin_user')->field('username')->where($map4)->find();
            $merchandiser2 = Db('admin_user')->field('username')->where($map4)->find();

            $historyrecord[$key]['check_aid'] = $check_aiddata['username'];
            // $historyrecord[$key]['check2_aid'] = $check2_aiddata['username'];
            $historyrecord[$key]['merchandiser'] = $merchandiserdata['username'];
            $historyrecord[$key]['treasurer'] = $treasurerdata['username'];
            $historyrecord[$key]['merchandiser2'] = $merchandiser2['username'];

             #延期+还款
             if( $historyrecord[$key]['predelay']) {
                 foreach($historyrecord[$key]['predelay'] as $k=>$v){
                     if(strpos($v['no_order'],'XQ') === false) {
                         $historyrecord[$key]['predelay'][$k]['ishk'] = 1;

                         if ($historyrecord[$key]['fourth_claim_date'] < $historyrecord[$key]['predelay'][$k]['pay_time']
                             && !is_null($historyrecord[$key]['fourth_claim_date'])
                         ) {
                             $historyrecord[$key]['predelay'][$k]['role'] = 'M1';//角色
                             $historyrecord[$key]['predelay'][$k]['roleName'] = $merchandiser2['username'];//角色姓名
                         } else {
                             $historyrecord[$key]['predelay'][$k]['role'] = 'M0';//角色
                             $historyrecord[$key]['predelay'][$k]['roleName'] = $merchandiserdata['username'];//角色姓名
                         }

                         //催收备注表
                         $whereRN['apply_id'] = $value['id'];
                         $whereRN['admin_uid'] = $GLOBALS['userInfo']['id'];
                         $whereRN['uid'] = $value['uid'];
                         $reminder = Db::name('reminder_note')->where($whereRN)->order('id desc')->find();
                         $historyrecord[$key]['predelay'][$k]['contact'] = $reminder['contact_type'];//联系方式
                         $historyrecord[$key]['predelay'][$k]['remark'] = $reminder['reminder_status'];//备注
                         $historyrecord[$key]['predelay'][$k]['contact_name'] = $reminder['contact_name'];//联系姓名方式
                     }
                 }
             }
         }
         
        
        // 资料补充
        $datainfo = Db::name('data_supplement')->where($maps)
                                               ->where('is_delete is null')
                                               ->field('dataname,datacontent,datatime,id,datatype,admin_id')
                                               ->select();

        foreach($datainfo as $key=>$value)
        {
           $where['id'] = $value['admin_id'];
           $admin_user = Db::name('admin_user')->where($where)->field('username')->find();
           $datainfo[$key]['datauser'] = $admin_user['username'];
        }
        $data['historyrecord']=$historyrecord;
        $data['datainfo']=$datainfo;


        //天机三位联系人
       $secret =  Db::name('secret_about')->where($maps)->find();
       $data['secret'] = json_decode($secret['four_contacts'],true);

       // 天机报告
       $creditinfo = Db::name('user_info')->where($maps)->field('operator_state2,operator_search_id,id_card,mongo_operator_report,operator_id,name,uid,is_extract,savehtml')->find();
       $bizData = array(
        'userId'    => $creditinfo['operator_id'],
        'mongoRes'  => $creditinfo['mongo_operator_report'],
        'channel'   => config('operator_channel'),
        'idNumber'  => $creditinfo['id_card'],
        'search_id' => $creditinfo['operator_search_id'],
        );
       $demo = report_detail($bizData);
       if($demo['code'] == 200){
            $emergency_analysis = $demo['data']['JsonData']['json']['emergency_analysis'];
            
            $phone_value = $demo['data']['JsonData']['json']['call_log'];
            $arr_phone = array();

            if(is_array($phone_value)) {
                foreach($phone_value as $key=>$value)
                {
                    $arr_phone[] = $value['phone'];
                }            
            }

            if(is_array($emergency_analysis)) {
                foreach($emergency_analysis as $key=>$value)
                {
                    if(in_array($value['phone'], $arr_phone))
                    {
                        $emergency_analysis[$key]['match'] = 1;

                    }else
                    {
                        $emergency_analysis[$key]['match'] = 0;
                    }

                }  
            }

            for ($i=0; $i < 10; $i++) { 
                $value = $demo['data']['JsonData']['json']['call_log'][$i];
                $call_log_ten[$i]  = $value;
                $call_log_ten[$i]['talk_minute'] = formatMoney($value['talk_seconds'] / 60);
                $call_log_ten[$i]['call_minute'] = formatMoney($value['call_seconds'] / 60);
                $call_log_ten[$i]['called_minute'] = formatMoney($value['called_seconds'] / 60);
            }
        }

       if(is_array($emergency_analysis)){
        foreach ($emergency_analysis as $key => $value) {
            if($value['phone'] == $data['secret'][$key]['phone']){
                $emergency_analysis[$key]['relation'] = $data['secret'][$key]['relation'];
            }
            $emergency_analysis[$key]['talk_minute'] = formatMoney($value['talk_seconds'] / 60);
        }
       }
       // 紧急联系人
       $data['emergency_analysis'] = $emergency_analysis;

       // 前十个联系人
       
       
       // $url = config('TXLSJ').$uid;
       $local_url = $_SERVER['SERVER_NAME'];
       $url = 'http://'.$local_url.'/admin/Scriptfile/getTelDetails?uid='.$uid;
       $txl = httpGet($url);
       $txl = json_decode($txl,true);
       if(!empty($txl)){
            for($i=0;$i<10;$i++)
            {
                foreach($txl['list'] as $key => $value) {
                    if($value['match'] == 1)
                    {
                        if($value['phone'] == $call_log_ten[$i]['phone'])
                        {
                            if(!$value['n']){
                                $call_log_ten[$i]['name'] = $value['name'];
                            }else{
                                $call_log_ten[$i]['name'] = $value['n'];
                            }
                            
                        }
                    }
                }
            }  
        }



       $data['call_log_ten'] = $call_log_ten;
        
 
       // print_r($data['call_log_ten']);exit;

        return $data;
    }

    /**
     * 历史延期
     * @author cxr <1481746137@qq.com>
     * @return $this
     */
    public function predelay(){
//        $where_yanqi['qh_user_order.no_order'] = ['like', '%XQ%']; // 总
        $where_yanqi['result_pay'] = ['eq', 'SUCCESS'];
        return $this->hasMany('UserOrder','apply_id','order_number')->where($where_yanqi);
    }

    /**
     * 历史还款
     * @author cxr <1481746137@qq.com>
     * @return $this
     */
    public function prerepay(){
        $map['result_pay'] = 'SUCCESS';
        $map['no_order'] = ['notlike', '%XQ%']; //不和延期订单混淆， 失误少了个这个条件
        return $this->hasMany('UserOrder','apply_id','order_number')->where($map)->order('pay_time desc');
    }
    
    /**
     * 通过id修改用户
     * @param  array   $param  [description]
     */
    public function updateDataById($param, $id)
    {
        $checkData = $this->where('id',$id)->find();

        if (!$checkData) {
            $this->error = '暂无此数据';
            return false;
        }
        if($param['sex']=='男'){
            $param['sex']=1;
        }elseif($param['sex']=='女'){
            $param['sex']=0;
        }
        $validate = validate($this->name);
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }
        $param['update_time']=date('Y-m-d H:i:s',time());;
        $re=$this->allowField(true)->save($param,['id'=>$id]);
        $arr=array();
        $arr['username']=$param['username'];
        $arr['phone']=$param['phone'];
        $re1=Db::name('user')->where('uid',$id)->update($arr);
        if($re || $re1){
            return true;
        }else{
            $this->error = '编辑失败';
            return false;
        }
    }
    public function getName($uid)
    {
        return $this->where('uid',$uid)->value("name");
    }
    public function getPhone($uid)
    {
        return $this->where('uid',$uid)->value("phone");
    }    
    public function resetDataById($id)
    {
        // 不能操作超级管理员
        if ($id == 1) {
            $this->error = '非法操作';
            return false;
        }
        $checkData = $this->where('uid',$id)->find();
        if (!$checkData) {
            $this->error = '暂无此数据';
            return false;
        }
        /*if($checkData['status']!=1){
            $this->error = '该账户已被删除或禁用！';
            return false;
        }*/
        $param=array();
        $param['password']=123456;
        $param['password'] = user_md5($param['password'],$auth_key = 'qhdkb');
        $param['last_login_time']=date('Y-m-d H:i:s',time());;
        $res=Db::name('user')->where('uid',$id)->update($param);
        if($res){
            return true;
        }else{
            $this->error = '重置失败';
            return false;
        }
    }
    /**
     * 获取所有子孙
     */
    public function getAllChild($id, &$data = [])
    {
        $map['pid'] = $id;
        $childIds = $this->where($map)->column($this->getPk());
        if (!empty($childIds)) {
            foreach ($childIds as $v) {
                $data[] = $v;
                $this->getAllChild($v, $data);
            }
        }
        return $data;
    }
    public function enableData($ids = [], $status = 1, $delSon = false)
    {
        if (empty($ids)) {
            $this->error = '修改失败';
            return false;
        }

        // 查找所有子元素
        if ($delSon && $status === '0') {
            foreach ($ids as $k => $v) {
                $childIds = $this->getAllChild($v);
                $ids = array_merge($ids, $childIds);
            }
            $ids = array_unique($ids);
        }
        $list=$this->where('id','in',$ids)->select();
        $list = modelo2array($list);
        $data['list'] = $list;
        $uids=array();
        foreach($data['list'] as &$v){
            $uids[]=$v['uid'];
        }
        try {
            Db::name('user')->where('uid','in',$uids)->setField('status', $status);
            return true;
        } catch (\Exception $e) {
            $this->error = '操作失败';
            return false;
        }
    }
    
    /**
     * [getInvitDataById 根据主键获取邀请人数详情]
     * @linchuangbin
     * @DateTime  
     * @param     string                   $id [主键]
     * @return    [array]
     */
    public function getInvitDataById($uid,$page, $limit)
    {
        $dataCount = $this->alias('a')
                    ->join('qh_invite_code b','a.uid = b.uid')
                    ->where('puid',$uid)
                    ->count('b.id');
        
        $invitName = $this->where('uid',$uid)->field('name')->find();
        $invitName = json_decode($invitName);
        $list = $this
        ->where(1);
        // 若有分页
        if ($page && $limit) {
            $list = $this->page($page, $limit);
        }
        
        $list=$this->alias('a')
        ->join('qh_invite_code b','a.uid = b.uid')
        ->field('a.name,a.qq,a.phone,a.zhima,b.create_time')
        ->where('b.puid',$uid)
        ->select();
        
        $list = modelo2array($list);
        $data['list'] = $list;
        $data['dataCount'] = $dataCount;
        $data['invitName'] = $invitName;
        return $data;
    }

}